package com.kongge.algorithm.demo;

import com.kongge.algorithm.list.ListNode;

/**
 * 定义一个函数，输入一个链表的头结点，反转该链表并输出反转链表的头结点
 * @author gaoshiqi
 *
 */
public class ReverseList implements IAlgorithm{

	public void execute() {
		ListNode<Integer> head = ListNode.createList(1, 2, 3, 4, 5, 6);
		head = reverseList(head);
		ListNode.printList(head);
	}
	
	private ListNode<Integer> reverseList(ListNode<Integer> head) {
		if (head == null || head.next == null) {
			return head;
		}
		ListNode<Integer> newHead = null;
		ListNode<Integer> curNode = head;
		while (curNode != null) {
			ListNode<Integer> nextNode = curNode.next;
			curNode.next = newHead;
			newHead = curNode;
			curNode = nextNode;
		}
		return newHead;
	}
}
